import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

import '../controller/auth_controller.dart';
import '../controller/navigation_controller.dart';
import '../controller/contract_controller.dart';
import '../controller/wallet_controller.dart';
import '../controller/invite_controller.dart';
import '../screens/main/main_page.dart';
import '../service/analytics_service.dart';
import '../widgets/login_dialog.dart';

class NavScreen extends StatefulWidget {
  const NavScreen({super.key});
  
  @override
  _NavScreenState createState() => _NavScreenState();
}

class _NavScreenState extends State<NavScreen> with TickerProviderStateMixin {
  final AuthController authController = Get.find<AuthController>();
  final NavigationController navController = Get.put(NavigationController());
  
  late TabController _tabController;
  
  final List<Widget> _screens = [
    MainPage(),
  ];
  
  final List<IconData> _icons = [
    MdiIcons.home,
    MdiIcons.wallet,
    MdiIcons.shareVariant,
    MdiIcons.menu,
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _icons.length, vsync: this);
    
    // 监听TabController的变化
    _tabController.addListener(() {
      if (!_tabController.indexIsChanging) {
        _handleTabChange(_tabController.index);
      }
    });
    
    // 监听NavigationController的变化，同步TabController
    ever(navController.currentIndex, (index) {
      if (_tabController.index != index) {
        _tabController.animateTo(index);
      }
    });
  }
  
  void _handleTabChange(int index) {
    try {
      // 检查权限
      if (!authController.isLoggedIn.value && (index != 0)) {
        // 未登录且尝试访问钱包或帮助页面
        _showLoginDialog();
        // 保持在首页
        _tabController.animateTo(0);
        navController.setCurrentIndex(0);
        return;
      }
      
      // 更新NavigationController
      navController.setCurrentIndex(index);
      
      // 在页面切换时触发API调用
      _triggerPageRefresh(index);
    } catch (e, stackTrace) {
      print('处理标签变化时出错: $e');
      // 记录错误但不中断应用流程
      AnalyticsService.recordError(
        e, 
        stackTrace,
        reason: 'Tab change error',
        fatal: false
      );
    }
  }
  
  /// 根据页面索引触发相应的API调用
  void _triggerPageRefresh(int index) {
    print('切换到页面索引: $index');
    
    // 记录屏幕浏览事件，使用try-catch包裹以避免可能的错误
    try {
      String screenName;
      switch (index) {
        case 0:
          screenName = 'main_page';
          break;
        case 1:
          screenName = 'wallet_page';
          break;
        case 2:
          screenName = 'referral_page';
          break;
        case 3:
          screenName = 'help_page';
          break;
        default:
          screenName = 'unknown_page';
      }
      
      // 使用Future.microtask延迟执行Firebase事件记录，避免在页面切换过程中立即执行
      Future.microtask(() {
        AnalyticsService.logScreenView(
          screenName: screenName,
          screenClass: 'NavScreen',
        );
      });
    } catch (e) {
      print('记录屏幕浏览事件失败: $e');
    }
    
    switch (index) {
      case 0: // 合约页面
        print('刷新合约页面数据');
        final contractController = Get.find<ContractController>();
        // contractController.getContractList(); // 移除自动加载，只在用户点击按钮时加载
        // contractController.getUserContractList();
        break;
        
      case 1: // 钱包页面
        print('刷新钱包页面数据');
        final walletController = Get.find<WalletController>();
        walletController.loadUserEarnings();
        walletController.loadWithdrawRecords();
        break;
        
      case 2: // 邀请页面
        print('刷新邀请页面数据');
        try {
          // 检查InviteController是否已注册，如果没有则先注册
          if (!Get.isRegistered<InviteController>()) {
            Get.put(InviteController());
          }
          final inviteController = Get.find<InviteController>();
          inviteController.loadInviteInfo();
        } catch (e, stackTrace) {
          print('InviteController 初始化或加载失败: $e');
          // 记录错误但不中断应用流程
          AnalyticsService.recordError(
            e, 
            stackTrace,
            reason: 'InviteController initialization error',
            fatal: false
          );
        }
        break;
        
      case 3: // 菜单页面
        print('检查菜单页面数据');
    
        break;
    }
  }
  
  void _showLoginDialog() {
    showDialog(
      context: context,
      builder: (context) => LoginDialog(),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double bottomSafa = MediaQuery.of(context).padding.bottom;
    
    return DefaultTabController(
      length: _icons.length,
      child: Scaffold(
        appBar: null,
        body: Obx(() => IndexedStack(
          index: navController.currentIndex.value,
          children: _screens,
        )),
        bottomNavigationBar: Container(
          padding: EdgeInsets.only(bottom: bottomSafa > 0 ? bottomSafa : 12.0),
          color: const Color(0xFF2A2A2A),
        ),
      ),
    );
  }
}